package com.sun.tetris.util;

import com.sun.tetris.exception.GameException;
import com.sun.tetris.object.Piece;
import com.sun.tetris.object.Square;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author 烛龙神
 * @Description TODO
 * @date 2021-07-27 21:00
 */
public class ImageUtil {

    private static final Log LOGGER = LogFactory.getLog(ImageUtil.class);

    public static BufferedImage getImage(String imagePath) {
        try {
            //使用ImageIO读取图片
            return ImageIO.read(new File(imagePath));
        } catch (IOException e) {
            //读取图片发生异常，抛出GameException
            ImageUtil.LOGGER.error(e.getMessage(),e);
            throw new GameException("read image error");
        }
    }

    /**
     * 在界面上画一个Piece对象
     * @param g
     * @param piece
     */
    public static void paintPiece(Graphics g, Piece piece) {
        if (piece == null) return;
        for (int i = 0; i < piece.getSquares().size(); i++) {
            Square s = piece.getSquares().get(i);
            g.drawImage(s.getImage(), s.getBeginX(), s.getBeginY(), null);
        }
    }
}
